package com.ruoyi.system.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.system.api.RemoteFileDataService;
import com.ruoyi.system.api.domain.File;
import com.ruoyi.system.domain.SysAppVersion;
import com.ruoyi.system.mapper.SysAppVersionMapper;
import com.ruoyi.system.service.IFileService;
import com.ruoyi.system.service.ISysAppVersionService;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysAppVersionServiceImpl implements ISysAppVersionService {

    @Autowired
    private SysAppVersionMapper sysAppVersionMapper;

    @Autowired
    private IFileService fileService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RemoteFileDataService remoteFileDataService;

    @Override
    public List<SysAppVersion> selectSysAppVersionList(SysAppVersion sysAppVersion) {
        return sysAppVersionMapper.selectSysAppVersionList(sysAppVersion);
    }

    @Override
    @Transactional
    public int insertSysAppVersion(SysAppVersion appVersion) throws IOException {
        verify(appVersion);
        if (sysAppVersionMapper.insertSysAppVersion(appVersion) == 1 && appVersion.getOnlineRelease() == 1) {
            sysAppVersionMapper.updateOnlineStatus(appVersion);
        }
        if (appVersion.getPackageAddress() != null && appVersion.getOnlineRelease() == 1) {
            generateCode(appVersion);
        }
        return 1;
    }

    /**
     * 生成app软件的二维码
     *
     * @param appVersion
     */
    public byte[] generateCode(SysAppVersion appVersion) {
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
//            QrCodeUtil.generate(appVersion.getPackageAddress(), config,FileUtil.file("D:/qrTest/qrcode" + "ewm" + ".jpg"));
        // 生成二维码到字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        QrCodeUtil.generate(appVersion.getPackageAddress(), config, "jpg", outputStream);
        byte[] bytes = outputStream.toByteArray();
        return bytes;
//        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
//                MediaType.ALL_VALUE, true, "qrcode.jpg");
//        try {
//            OutputStream os = fileItem.getOutputStream();
//            os.write(bytes);
//            os.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);
//        File file1 = new File();
//        file1.setGroupId(appVersion.getId());
//        file1.setTypeId(42);
//        file1.setFile(multipartFile);
//        // 上传文件
//        remoteFileDataService.autoUploadFileSave(file1, SecurityConstants.INNER);
    }


    /**
     * 新增或者编辑的验证的条件
     *
     * @param appVersion
     */
    private void verify(SysAppVersion appVersion) {
        if (appVersion.getVersionId() != null) {
            Integer count = jdbcTemplate.queryForObject("select count(*) from sys_app_version where version_id <> ? and version =?", Integer.class, appVersion.getVersionId(), appVersion.getVersion().trim());
            if (count > 0) {
                throw new ServiceException(appVersion.getVersion() + "已存在!");
            }
        } else {
            Integer count1 = jdbcTemplate.queryForObject("select count(*) from sys_app_version where  version = ?", Integer.class, appVersion.getVersion());
            if (count1 > 0) {
                throw new ServiceException(appVersion.getVersion() + "已存在!");
            }
        }
        //包地址
        if (appVersion.getOnlineRelease() == 1 && StringUtils.isEmpty(appVersion.getPackageAddress())) {
            throw new ServiceException("请选择包地址");
        }
        if (appVersion.getVersionId() == null) {
            appVersion.setVersionId(Seq.getSeqId());
        }
        if (StringUtils.isNotEmpty(appVersion.getFileList())) {
            List<Long> fileIdList = appVersion.getFileList().stream().map(File::getFileId).collect(Collectors.toList());
            if (!fileService.saveFile(appVersion.getVersionId(), 38, fileIdList)) {
                throw new ServiceException("安装包更新失败");
            }
        }

    }


    @Override
    public SysAppVersion selectSysAppVersionById(Long versionId) {
        SysAppVersion sysAppVersion = sysAppVersionMapper.selectSysAppVersionById(versionId);
        // 38 安装包文件类型
        List<File> fileList = fileService.selectFileListByGroupId(versionId, "38");
        if (fileList.size() > 0) {
            sysAppVersion.setFileList(fileList);
        }
        return sysAppVersion;
    }

    @Override
    @Transactional
    public int updateSysAppVersion(SysAppVersion appVersion) throws IOException {
        //平台多选
        verify(appVersion);
        if (sysAppVersionMapper.updateSysAppVersion(appVersion) == 1 && appVersion.getOnlineRelease() == 1) {
            sysAppVersionMapper.updateOnlineStatus(appVersion);
        }
        if (appVersion.getPackageAddress() != null && appVersion.getOnlineRelease() == 1) {
            generateCode(appVersion);
        }
        return 1;
    }

    @Override
    public int deleteSysAppVersionByIds(Long[] versionIds) {
        return sysAppVersionMapper.deleteSysAppVersionByVersionIds(versionIds);
    }

    @Override
    public Map<String, Object> latest(SysAppVersion appVersion) {
        //前端app传入的版本id
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(appVersion.getVersion()) || StringUtils.isEmpty(appVersion.getAppId())) {
            map.put("code", -102);
            map.put("message", "请检查传参是否填写正确");
            return map;
        }
        String version = appVersion.getVersion();
        SysAppVersion sysAppVersion = sysAppVersionMapper.selectLatestVersion(appVersion);
        if (sysAppVersion == null) {
            map.put("code", -101);
            map.put("message", "暂无更新或检查appid是否填写正确");
        } else {
            if (sysAppVersion.getVersion().equals(version)) {
                //相同的版本不需要更新
                map.put("code", 0);
                map.put("message", "当前版本已经是最新版的,不需要更新");
            } else {
                map.put("appId", sysAppVersion.getAppId());
                map.put("version", sysAppVersion.getVersion());
                map.put("packageAddress", sysAppVersion.getPackageAddress());
                map.put("content", sysAppVersion.getContent());
                map.put("title", sysAppVersion.getTitle());
                map.put("forceUpdate", sysAppVersion.getForceUpdate());
                if (sysAppVersion.getPackageType() == 1) {
                    map.put("code", 101);
                    map.put("message", "wgt更新");
                } else {
                    map.put("code", 102);
                    map.put("message", "整包更新");
                }
            }
        }
        return map;
    }

    @Override
    public byte[] selectqr() {
        SysAppVersion version = new SysAppVersion();
        version.setAppId("__UNI__1456F51");
        SysAppVersion sysAppVersion = sysAppVersionMapper.selectLatestVersion(version);
        if(sysAppVersion != null){
            return generateCode(sysAppVersion);
        }
        return null;
    }

}
